<template>
  <el-container class="my-container">
    <el-header height="10">
      <el-space wrap>
        <transition name="el-zoom-in-top">
          <el-form v-show="showSearchForm" ref="searchFormRef" :inline="true" :model="searchData"
                   style="padding-top: 10px;">
            <template v-if="Object.keys(category.searchConfig || {}).length > 0"
                      v-for="(searchFiled, fieldName) in category.searchConfig">
              <el-form-item :label="searchFiled.desc" :prop="fieldName">
                <el-input v-model="searchData[fieldName]" :placeholder="'请填写' + searchFiled.desc" clearable/>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="任务名称" prop="id">
                <el-input v-model="searchData.id" placeholder="主表ID" clearable/>
              </el-form-item>
              <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="searchData.taskName" placeholder="请填写任务名称" clearable/>
              </el-form-item>
              <el-form-item label="当前处置人" prop="handleUserName">
                <el-input v-model="searchData.handleUserName" placeholder="请填写当前处置人" clearable/>
              </el-form-item>
            </template>

            <el-form-item>
              <el-button type="primary" @click="loadTableData">查询</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </transition>
        <el-button v-show="showSearchForm" type="warning" @click="showSearchForm=false" icon="Hide">隐藏查询条件
        </el-button>
        <el-button v-show="!showSearchForm" type="primary" @click="showSearchForm=true" icon="View">展示查询条件
        </el-button>
        <el-button type="primary" @click="configJsonDrawer=true" icon="Tickets">业务配置数据</el-button>
        <el-button type="info" @click="refreshSillyCache" icon="Refresh">刷新缓存</el-button>
        <el-button type="success" icon="Plus"
                   @click="editBusinessData({ id: '', processKey: '', processId: '', taskId: '', taskList: [], root: null, nodeRoot: null})">
          新增数据
        </el-button>
        <el-drawer v-model="configJsonDrawer" :title="category.processDesc" size="50%">
          <el-card>
            <json-viewer style="padding: 0;" :value="category" :expand-depth="6" copyable></json-viewer>
          </el-card>
        </el-drawer>
      </el-space>
    </el-header>

    <el-main class="my-container-main">
      <el-tabs v-model="activeTab">
        <el-tab-pane name="todo">
          <template #label>
            <el-icon>
              <EditPen/>
            </el-icon>
            待办任务
          </template>
        </el-tab-pane>
        <el-tab-pane name="history" :lazy="true">
          <template #label>
            <el-icon>
              <Finished/>
            </el-icon>
            历史任务
          </template>
        </el-tab-pane>
        <el-tab-pane name="query" :lazy="true">
          <template #label>
            <el-icon>
              <Memo/>
            </el-icon>
            全部数据
          </template>
        </el-tab-pane>
      </el-tabs>

      <el-table v-show="activeTab==='todo'" :data="tableData" border v-loading="loading" height="100%"
                style="width: 100%;"
      >
        <el-table-column prop="id" type="index" label="序号" width="60">
          <template #default="{row, $index}">
            {{ 1 + $index + (page.size * (page.pageNo - 1)) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="230">
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="editBusinessData(row)">业务操作</el-button>
            <el-button link type="primary" size="small" @click="editProcessData(row)">流程修改</el-button>
            <el-button link type="primary" size="small" @click="editRootData(row)">数据修改</el-button>
          </template>
        </el-table-column>
        <template v-if="category.admin?.todoColumns?.length > 0" v-for="columns in category.admin.todoColumns">
          <el-table-column :prop="columns.prop" :label="columns.label" :width="columns.width" sortable
                           show-overflow-tooltip/>
        </template>
        <template v-else>
          <el-table-column prop="id" label="主表ID" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processKey" label="流程KEY" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processVersion" label="流程版本" sortable show-overflow-tooltip width="110"/>
          <el-table-column prop="taskName" label="任务名称" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="handleUserName" label="当前处置人" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="status" label="状态" sortable show-overflow-tooltip width="80"/>
          <el-table-column prop="createDate" label="创建时间" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="updateDate" label="更新时间" sortable show-overflow-tooltip width="180"/>
        </template>
      </el-table>
      <el-table v-show="activeTab==='history'" :data="tableData" border v-loading="loading" height="100%"
                style="width: 100%;">
        <el-table-column prop="id" type="index" label="序号" width="60">
          <template #default="{row, $index}">
            {{ 1 + $index + (page.size * (page.pageNo - 1)) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="editProcessData(row)">流程修改</el-button>
            <el-button link type="primary" size="small" @click="editRootData(row)">数据修改</el-button>
          </template>
        </el-table-column>
        <template v-if="category.admin?.historyColumns?.length > 0"
                  v-for="columns in category.admin.historyColumns">
          <el-table-column :prop="columns.prop" :label="columns.label" :width="columns.width" sortable
                           show-overflow-tooltip/>
        </template>
        <template v-if="category.admin?.todoColumns?.length > 0" v-for="columns in category.admin.todoColumns">
          <el-table-column :prop="columns.prop" :label="columns.label" :width="columns.width" sortable
                           show-overflow-tooltip/>
        </template>
        <template v-else>
          <el-table-column prop="id" label="主表ID" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processKey" label="流程KEY" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processVersion" label="流程版本" sortable show-overflow-tooltip width="110"/>
          <el-table-column prop="taskName" label="任务名称" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="handleUserName" label="当前处置人" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="status" label="状态" sortable show-overflow-tooltip width="80"/>
          <el-table-column prop="createDate" label="创建时间" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="updateDate" label="更新时间" sortable show-overflow-tooltip width="180"/>
        </template>
      </el-table>
      <el-table v-show="activeTab==='query'" :data="tableData" border v-loading="loading" height="100%"
                style="width: 100%;">
        <el-table-column prop="id" type="index" label="序号" width="60">
          <template #default="{row, $index}">
            {{ 1 + $index + (page.size * (page.pageNo - 1)) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="editProcessData(row)">流程修改</el-button>
            <el-button link type="primary" size="small" @click="editRootData(row)">数据修改</el-button>
          </template>
        </el-table-column>
        <template v-if="category.admin?.queryColumns?.length > 0"
                  v-for="columns in category.admin.queryColumns">
          <el-table-column :prop="columns.prop" :label="columns.label" :width="columns.width" sortable
                           show-overflow-tooltip/>
        </template>
        <template v-if="category.admin?.todoColumns?.length > 0" v-for="columns in category.admin.todoColumns">
          <el-table-column :prop="columns.prop" :label="columns.label" :width="columns.width" sortable
                           show-overflow-tooltip/>
        </template>
        <template v-else>
          <el-table-column prop="id" label="主表ID" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processKey" label="流程KEY" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="processVersion" label="流程版本" sortable show-overflow-tooltip width="110"/>
          <el-table-column prop="taskName" label="任务名称" sortable show-overflow-tooltip width="250"/>
          <el-table-column prop="handleUserName" label="当前处置人" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="status" label="状态" sortable show-overflow-tooltip width="80"/>
          <el-table-column prop="createDate" label="创建时间" sortable show-overflow-tooltip width="180"/>
          <el-table-column prop="updateDate" label="更新时间" sortable show-overflow-tooltip width="180"/>
        </template>
      </el-table>

      <el-drawer v-if="newJsonDataDrawer" :key="'newJsonDataDrawer'" v-model="newJsonDataDrawer"
                 :title="category.processDesc + '-业务数据操作'" size="70%">

        <div>
          <el-select v-if="!currentRow.taskId" v-model="currentRow.processKey" placeholder="请选择流程KEY">
            <el-option
                v-for="(masterConfig, masterKey) in category.master"
                :key="masterConfig.processKey"
                :value="masterConfig.processKey"
                :label="masterConfig.processKey">
            </el-option>
          </el-select>
          <el-select v-if="!currentRow.taskId" v-model="newJsonDataNodeKey" placeholder="请选择节点"
                     @change="refreshNewJsonData();">
            <el-option
                v-for="(nodeConfig, nodeKey) in category.master[currentRow.processKey || category.lastProcessKey]?.node"
                :key="nodeConfig.nodeKey"
                :value="nodeConfig.nodeKey"
                :label="nodeConfig.nodeKey + ' - ' + nodeConfig.nodeName">
            </el-option>
          </el-select>
          <el-select v-if="currentRow.taskId" v-model="newJsonDataTaskId" placeholder="请选择操作节点任务">
            <el-option v-for="t in currentRow.taskList"
                       :key="t.taskId"
                       :value="t.taskId"
                       :label="t.nodeKey + ' - ' + t.nodeName + ' - ' + t.taskId">
            </el-option>
          </el-select>

          <el-button v-show="!newJsonDataDescFlag" type="warning" size="small"
                     @click="newJsonDataDescFlag = true;refreshNewJsonData();">
            切换到描述JSON
          </el-button>
          <el-button v-show="newJsonDataDescFlag" type="primary" size="small"
                     @click="newJsonDataDescFlag = false;refreshNewJsonData();">
            切换到数据JSON
          </el-button>
          <el-button v-show="currentRow.processKey || currentRow.processId" type="primary" size="small"
                     @click="showProcessBpmn = !showProcessBpmn">
            {{ showProcessBpmn ? '隐藏' : '查看' }}流程图
          </el-button>
        </div>

        <SillyBpmnViewer v-if="showProcessBpmn" :category="categoryKey"
                         :process-id="currentRow.processId" :process-key="currentRow.processKey"
                         @click-element="newJsonDataNodeKey=$event.id; refreshNewJsonData();"></SillyBpmnViewer>
        <codemirror
            v-model="newJsonData"
            placeholder="在此输入JSON格式数据"
            :lineNumbers="true"
            :lineWrapping="true"
            :autoFormatOnLoad="true"
            :extensions="extensions"
        />

        <template #footer v-if="!newJsonDataDescFlag">
          <el-button type="info" icon="Check" @click="saveNewJsonData(false)">保存</el-button>
          <el-button type="primary" icon="Promotion" @click="saveNewJsonData(true)">提交</el-button>
        </template>
      </el-drawer>

      <el-drawer v-if="jsonDataDrawer" :key="'jsonDataDrawer' + currentRow.id" v-model="jsonDataDrawer"
                 :title="category.processDesc + '-数据修改'" size="70%">
        <el-tabs v-model="jsonDataDrawerActiveTab" type="border-card">
          <el-tab-pane name="detail" label="数据详情">
            <el-scrollbar class="data-tab-pane">
              <el-card shadow="hover">
                <template
                    v-for="(nodeConfig, nodeKey) in category.master[currentRow.processKey || category.lastProcessKey].node">
                  <el-descriptions v-if="currentRow.nodeRoot[nodeKey]" :column="4" border>
                    <template #title>
                      <i class="el-icon-s-flag"></i> {{ nodeConfig.nodeName }}
                    </template>

                    <template #default>
                      <el-descriptions-item :span="2">
                        <template #label>
                          <i class="el-icon-user"></i>操作人
                        </template>
                        {{ currentRow.nodeRoot[nodeKey]?.currentUserName }}
                      </el-descriptions-item>
                      <el-descriptions-item :span="2">
                        <template #label>
                          <i class="el-icon-date"></i>操作时间
                        </template>
                        {{ DateFormat(currentRow.nodeRoot[nodeKey]?.currentDate, null) }}
                      </el-descriptions-item>

                      <template v-for="(variableConfig, variableName) in nodeConfig.variable">
                        <el-descriptions-item
                            v-if="variableConfig.variableType !== 'entity' && variableConfig.variableType !== 'newProcesses'">
                          <template #label>
                            {{ variableConfig.desc || variableName }}
                          </template>
                          <DescriptionCell v-model="crRef" :variable-config="variableConfig"></DescriptionCell>
                        </el-descriptions-item>
                      </template>
                    </template>
                  </el-descriptions>

                  <template v-for="(variableConfig, variableName) in nodeConfig.variable">
                    <template
                        v-if="variableConfig.variableType === 'entity' || variableConfig.variableType === 'newProcesses'">
                      <el-card shadow="never">
                        <template #header>
                          <div class="card-header">
                            {{ variableConfig.desc || variableName }}
                          </div>
                        </template>
                        <DescriptionCell v-model="crRef" :variable-config="variableConfig"></DescriptionCell>
                      </el-card>
                    </template>
                  </template>
                </template>
              </el-card>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="root" label="扁平化数据">
            <el-scrollbar class="data-tab-pane">
              <codemirror
                  v-model="currentRootData"
                  placeholder="Code gose here..."
                  :lineNumbers="true"
                  :lineWrapping="true"
                  :autoFormatOnLoad="true"
                  :extensions="extensions"
              />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="nodeRoot" label="节点化数据" :lazy="true">
            <el-scrollbar class="data-tab-pane">
              <codemirror
                  v-model="currentNodeRootData"
                  placeholder="Code gose here..."
                  :lineNumbers="true"
                  :lineWrapping="true"
                  :autoFormatOnLoad="true"
                  :extensions="extensions"
              />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="editRoot" label="修改数据">
            <el-scrollbar class="data-tab-pane">
              <el-form ref="taskFormRef2" :inline="true" :model="taskOptionForm">
                <el-form-item v-if="currentRow.taskList.length > 1" label="操作任务选择" prop="taskId">
                  <el-select v-model="taskOptionForm.taskId" placeholder="请选择任务" clearable>
                    <el-option v-for="t in currentRow.taskList"
                               :key="t.taskId"
                               :value="t.taskId"
                               :label="t.nodeKey + ' - ' + t.nodeName + ' - ' + t.taskId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="节点选择" prop="nodeKey">
                  <el-select v-model="taskOptionForm.nodeKey" placeholder="请选择节点" clearable>
                    <el-option
                        v-for="(nodeConfig, nodeKey) in category.master[currentRow.processKey || category.lastProcessKey].node"
                        :key="nodeConfig.nodeKey"
                        :value="nodeConfig.nodeKey"
                        :label="nodeConfig.nodeKey + ' - ' + nodeConfig.nodeName">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="JSON参数" prop="paramsJson">
                  <el-input type="textarea" v-model="taskOptionForm.paramsJson"
                            autosize style="width: 800px"
                            placeholder="请填写JSON参数" show-word-limit clearable/>
                </el-form-item>

              </el-form>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="resume" label="流程履历" :lazy="true">
            <el-scrollbar class="data-tab-pane">
              <SillyResume :category="categoryKey" :master-id="currentRow.id"/>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>

        <template #footer>
          <el-button type="primary" v-show="jsonDataDrawerActiveTab === 'editRoot'"
                     @click="saveRootData">提交
          </el-button>
          <el-button type="warning"
                     v-show="jsonDataDrawerActiveTab === 'root' || jsonDataDrawerActiveTab === 'nodeRoot'"
                     @click="rockBackRootData">重置数据
          </el-button>
          <el-button type="danger" v-show="jsonDataDrawerActiveTab === 'editRoot'" @click="deleteData">数据删除
          </el-button>
        </template>
      </el-drawer>

      <el-drawer v-if="processDataDrawer" :key="'processDataDrawer' + currentRow.id" v-model="processDataDrawer"
                 :title="category.processDesc + '-流程修改'" size="80%">
        <el-tabs v-model="processDataDrawerActiveTab" type="border-card">
          <el-tab-pane name="detail" label="任务操作" :lazy="true">
            <el-scrollbar class="data-tab-pane-process">
              <el-form ref="taskFormRef1" :inline="true" :model="taskOptionForm">
                <el-form-item v-if="currentRow.taskList.length > 1" label="操作任务选择" prop="taskId">
                  <el-select v-model="taskOptionForm.taskId" placeholder="请选择任务">
                    <el-option v-for="t in currentRow.taskList"
                               :key="t.taskId"
                               :value="t.taskId"
                               :label="t.nodeKey + ' - ' + t.nodeName + ' - ' + t.taskId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="节点选择" prop="nodeKey">
                  <el-select v-model="taskOptionForm.nodeKey" placeholder="请选择节点" clearable>
                    <el-option
                        v-for="(nodeConfig, nodeKey) in category.master[currentRow.processKey || category.lastProcessKey].node"
                        :key="nodeConfig.nodeKey"
                        :value="nodeConfig.nodeKey"
                        :label="nodeConfig.nodeKey + ' - ' + nodeConfig.nodeName">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="原因" prop="reason">
                  <el-input v-model="taskOptionForm.reason" placeholder="请填写原因" clearable/>
                </el-form-item>
                <el-form-item label="人员选择" prop="userId">
                  <el-select-v2 v-model="taskOptionForm.userId" placeholder="请选择人员"
                                clearable filterable
                                :options="userArr">
                  </el-select-v2>
                </el-form-item>
                <el-form-item label="JSON参数" prop="paramsJson">
                  <el-input type="textarea" v-model="taskOptionForm.paramsJson"
                            autosize style="width: 800px"
                            placeholder="请填写JSON参数" clearable/>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="reStart">流程重启</el-button>
                  <el-button type="warning" @click="flow">任务流转</el-button>
                  <el-button type="danger" @click="reject">任务驳回</el-button>
                  <el-button type="danger" @click="jump" plain>流程跳转</el-button>
                </el-form-item>
              </el-form>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="viewer" label="流程图" :lazy="true">
            <el-scrollbar class="data-tab-pane-process">
              <SillyBpmnViewer :category="categoryKey" :process-id="currentRow.processId"
                               :resumes="resumeList"></SillyBpmnViewer>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane name="resume" label="流程履历" :lazy="true">
            <el-scrollbar class="data-tab-pane-process">
              <SillyResume :category="categoryKey" :master-id="currentRow.id" @loaded="resumeLoaded"/>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </el-drawer>

    </el-main>

    <el-footer height="auto">
      <el-pagination @size-change="page.pageNo = 1; loadTableData();" @current-change="loadTableData();"
                     v-model:current-page="page.pageNo" :page-sizes="[1, 10, 20, 50, 100, 1000, 5000]"
                     v-model:page-size="page.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="page.total">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script lang="ts" setup>
import {reactive, ref, watch, onMounted} from 'vue';
import {useUserStore, useCategoryStore, useUserOptionStore} from "@/core/common/StorageUtil";
import {copyNotEmpty} from "@/core/common/ObjectUtil.js";
import {
  addOrSaveMap,
  deleteMaster,
  flowTask,
  historyPage, jumpProcess,
  queryPage,
  refreshCache,
  rejectTask, saveFields,
  todoPage
} from "@/core/api/service.js";
import type {FormInstance} from 'element-plus'
import {ElMessage} from "element-plus";
import {Codemirror} from "vue-codemirror";
import {oneDark} from "@codemirror/theme-one-dark";
import {json} from "@codemirror/lang-json";
import {DateFormat} from "@/core/common/DateUtil";
import SillyBpmnViewer from "@/components/bpmn/SillyBpmnViewer.vue";
import {storeToRefs} from "pinia";
import {EditPen, Finished, Memo} from "@element-plus/icons-vue";
import DescriptionCell from "@/components/description/SillyDescriptionCell.vue";
import {Resume} from "@/core/entity/Resume";

const props = defineProps(['category'])
const categoryKey = props.category;
const categoryStore = useCategoryStore();
onMounted(() => {
  categoryStore.setActive(categoryKey);
});
const a = categoryStore.getCategory(categoryKey);
const category = ref(a);

const userOptionStore = useUserOptionStore();

const resumeList = reactive<Resume[]>([]);

const searchFormRef = ref<FormInstance>();
const taskFormRef1 = ref<FormInstance>();
const taskFormRef2 = ref<FormInstance>();

const showSearchForm = ref<boolean>(userOptionStore.showSearchForm);
watch(showSearchForm, (n, o) => {
  userOptionStore.setShowSearchForm(n)
});

const configJsonDrawer = ref<boolean>(false);
const loading = ref<boolean>(false);
const tableData = reactive<any[]>([]);
const page = reactive({
  size: 10,
  pageNo: 1,
  total: 0,
});

const activeTab = ref("todo");
watch(activeTab, (n, o) => {
  page.pageNo = 1;
  loadTableData();
});

const baseSearchData = reactive({
  queryRoot: true,
  queryNodeRoot: true,
});
const searchData = reactive({});

const taskOptionForm = reactive({masterId: '', taskId: '', nodeKey: '', reason: '', userId: '', paramsJson: ''});

const newJsonDataDrawer = ref(false);
const jsonDataDrawer = ref(false);
const processDataDrawer = ref(false);
const showProcessBpmn = ref(false);
const jsonDataDrawerActiveTab = ref("detail");
const processDataDrawerActiveTab = ref("detail");
const currentRow = reactive({
  id: '',
  processKey: '',
  processId: '',
  taskId: '',
  taskList: [],
  root: null,
  nodeRoot: null
});
const crRef = ref(currentRow)
const newJsonData = ref("");
const newJsonDataDescFlag = ref(false);
const newJsonDataTaskId = ref("");
const newJsonDataNodeKey = ref("");
const currentRootData = ref("");
const currentNodeRootData = ref("");

const user = useUserStore();
const {userArr, userId} = storeToRefs(user);

watch(() => user.userId, (n, o) => {
  loadTableData();
});

function resumeLoaded(resumes: Resume[]) {
  resumeList.length = 0;
  if (resumes && resumes.length > 0) {
    resumeList.push(...resumes);
  }
}

const refreshNewJsonData = () => {
  const processKey = currentRow.processKey;
  const nodeKey = newJsonDataNodeKey.value;
  const variableObj = category.value.master[processKey].node[nodeKey].variable;
  if (newJsonDataDescFlag.value) {
    newJsonData.value = JSON.stringify(variableObj, null, 2);
  } else {
    const jsonObj: any = {};
    for (let key in variableObj) {
      if (variableObj.hasOwnProperty(key)) {
        if (variableObj[key].finalText) {
          continue;
        }

        let fbt = "";
        if (!variableObj[key].required) {
          fbt = "非必填";
        }
        if (variableObj[key].variableType === 'list' || variableObj[key].variableType.endsWith("s")) {
          jsonObj[key] = fbt ? [fbt] : [];
        } else if (variableObj[key].variableType === 'number') {
          jsonObj[key] = fbt ? -1 : 0;
        } else if (variableObj[key].variableType === 'date') {
          jsonObj[key] = fbt ? DateFormat(1, 'yyyy-MM-dd') : DateFormat(new Date, 'yyyy-MM-dd');
        } else if (variableObj[key].variableType === 'dateTime') {
          jsonObj[key] = fbt ? DateFormat(1, 'yyyy-MM-dd hh:mm:ss') : DateFormat(new Date, 'yyyy-MM-dd hh:mm:ss');
        } else if (variableObj[key].variableType === 'entity') {
          if (variableObj[key].params.entityConfig.arrayData) {
            jsonObj[key] = [{"必填": fbt ? fbt : '必填'}];
          } else {
            jsonObj[key] = {"必填": fbt ? fbt : '必填'};
          }
        } else if (variableObj[key].variableType === 'newProcess') {
          jsonObj[key] = {"必填": fbt ? fbt : '必填'};
        } else if (variableObj[key].variableType === 'newProcesses') {
          jsonObj[key] = [{"必填": fbt ? fbt : '必填'}];
        } else {
          jsonObj[key] = (variableObj[key].defaultText || '') + fbt;
        }
      }
    }
    newJsonData.value = JSON.stringify(jsonObj, null, 2);
  }
}

function loadTableData() {
  loading.value = true;
  const pageTotalFieldName = category.value.admin.pageTotalFieldName;
  const pageSizeFieldName = category.value.admin.pageSizeFieldName;
  const pageNoFieldName = category.value.admin.pageNoFieldName;
  const recordsFieldName = category.value.admin.recordsFieldName;

  const params = copyNotEmpty({
    ...baseSearchData,
    ...searchData,
  });
  params[pageSizeFieldName] = page.size;
  params[pageNoFieldName] = page.pageNo;

  let pe: Promise<any>;
  if (activeTab.value === 'todo') {
    pe = todoPage(categoryKey, params);
  } else if (activeTab.value === 'history') {
    pe = historyPage(categoryKey, params);
  } else if (activeTab.value === 'query') {
    pe = queryPage(categoryKey, params);
  } else {
    loading.value = false;
    return;
  }
  pe.then((data: any) => {
    const records = data[recordsFieldName];
    tableData.length = 0;
    tableData.push(...records);
    page.total = data[pageTotalFieldName];
    loading.value = false;
  }).catch(err => {
    loading.value = false;
  });
}

const resetForm = () => {
  searchFormRef.value?.resetFields();
  loadTableData();
}

const extensions = [json(), oneDark];

const editRootData = (row: any) => {
  const {root, nodeRoot} = row;
  Object.assign(currentRow, row);
  jsonDataDrawer.value = true;
  currentRootData.value = JSON.stringify(root, null, 4);
  currentNodeRootData.value = JSON.stringify(nodeRoot, null, 4);
  taskOptionForm.taskId = currentRow.taskId;
  taskOptionForm.masterId = currentRow.id;
};

const editProcessData = (row: any) => {
  const {root, nodeRoot} = row;
  Object.assign(currentRow, row);
  processDataDrawer.value = true;
  currentRootData.value = JSON.stringify(root, null, 4);
  currentNodeRootData.value = JSON.stringify(nodeRoot, null, 4);
  taskOptionForm.taskId = currentRow.taskId;
  taskOptionForm.masterId = currentRow.id;
};

const editBusinessData = (row: any) => {
  Object.assign(currentRow, row);
  newJsonData.value = '';
  newJsonDataTaskId.value = currentRow.taskId;
  newJsonDataNodeKey.value = row?.taskObj?.nodeKey;
  if (newJsonDataNodeKey.value) {
    refreshNewJsonData();
  }
  newJsonDataDrawer.value = true;
}

const saveNewJsonData = (submit: boolean) => {
  loading.value = true;
  let params;
  try {
    params = JSON.parse(newJsonData.value);
  } catch (e) {
    params = {};
  }
  if (currentRow.taskId) {
    params.taskId = currentRow.taskId;
  }
  params.submit = submit;
  addOrSaveMap(categoryKey, params).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    processDataDrawer.value = false;
    loadTableData();
  }).catch(err => {
    loading.value = false;
  })
}

const rockBackRootData = () => {
  const {root, nodeRoot} = currentRow;
  jsonDataDrawer.value = true;
  currentRootData.value = JSON.stringify(root, null, 4);
  currentNodeRootData.value = JSON.stringify(nodeRoot, null, 4);
};

const saveRootData = () => {
  loading.value = true;
  const {masterId, nodeKey, taskId, paramsJson} = taskOptionForm;
  let params;
  try {
    params = JSON.parse(paramsJson);
  } catch (e) {
    params = {};
  }
  saveFields(categoryKey, masterId, nodeKey, taskId, params).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    processDataDrawer.value = false;
    loadTableData();
  }).catch(err => {
    loading.value = false;
  })
}

const deleteData = () => {
  loading.value = true;
  const {id} = currentRow;
  deleteMaster(categoryKey, id).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    jsonDataDrawer.value = false;
  }).catch(err => {
    loading.value = false;
  })
};

const refreshSillyCache = () => {
  refreshCache(categoryKey).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loadTableData();
  })
}

const addSillyData = () => {

}

const reStart = () => {

}

const flow = () => {
  loading.value = true;
  const {taskId, nodeKey, userId, reason} = taskOptionForm;
  flowTask(categoryKey, taskId, userId, reason).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    processDataDrawer.value = false;
    loadTableData();
  }).catch(err => {
    loading.value = false;
  })
}

const reject = () => {
  loading.value = true;
  const {taskId, nodeKey, userId, reason} = taskOptionForm;
  rejectTask(categoryKey, taskId, nodeKey, reason, userId, false).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    processDataDrawer.value = false;
    loadTableData();
  }).catch(err => {
    loading.value = false;
  })
}

const jump = () => {
  loading.value = true;
  const {masterId, nodeKey, reason, paramsJson} = taskOptionForm;
  let params;
  try {
    params = JSON.parse(paramsJson);
  } catch (e) {
    params = {};
  }
  jumpProcess(categoryKey, masterId, nodeKey, reason, params).then(msg => {
    ElMessage({
      showClose: true,
      message: msg,
      type: 'success',
    });
    loading.value = false;
    processDataDrawer.value = false;
    loadTableData();
  }).catch(err => {
    loading.value = false;
  })
}

loadTableData();

</script>

<script lang="ts">
import {Codemirror} from "vue-codemirror";
import SillyResume from "@/components/bpmn/SillyResume.vue";

export default {
  name: "CategoryTable",
  props: ['category'],
  components: {
    Codemirror, SillyResume
  }
}
</script>

<style scoped>
.my-container {
  height: calc(100vh - 140px);
}

.my-container-main {
  display: flex;
  flex-direction: column;
  padding-top: 0;
  padding-bottom: 0;
}

.data-tab-pane {
  width: 100%;
  height: calc(100vh - 250px);
}

.data-tab-pane-process {
  width: 100%;
  height: calc(100vh - 190px);
}
</style>